import axios from "axios"
import type { Song } from "@/types/song"
import type { Playlist } from "@/types/playlist"
import type { MV } from "@/types/mv"
import type { Album } from "@/types/album"
import type { UserProfile, UserFollower, UserFollowing } from "@/types/user"
import type { CommentResponse, ReplyResponse } from "@/types/comment"
import type { ParamValue } from "next/dist/server/request/params"

const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || "http://localhost:8888/api"

// Define AlbumGenreId type
type AlbumGenreId = number | string
type ArtistGenreId = number | string

// Create an axios instance
const apiClient = axios.create({
    baseURL: API_BASE_URL,
    headers: {
        "Content-Type": "application/json",
    },
})

// Add a response interceptor to handle authentication errors
apiClient.interceptors.response.use(
    (response) => {
        return response
    },
    (error) => {
        // Handle 401 Unauthorized errors
        if (error.response && error.response.status === 401) {
            // Clear token and redirect to login
            localStorage.removeItem("token")
            localStorage.removeItem("userId")
            localStorage.removeItem("username")
            localStorage.removeItem("avatar")
            window.location.href = "/login"
        }

        return Promise.reject(error)
    },
)

// Replace the fetchAlbum function with this updated version
export const fetchAlbum = async (id: string, userId?: number) => {
    const params = userId ? { userId } : {}
    const response = await apiClient.get(`/albums/${id}`, { params })
    return response.data.data
}

export const fetchAlbums = async (params: {
    page?: number
    limit?: number
    genreId?: AlbumGenreId | null
    regionId?: number
    featured?: boolean
    languageId?: number
}) => {
    const response = await apiClient.get("/albums", { params })
    return response.data.data
}

// 添加获取歌手列表的接口函数
export const getArtists = async (params: {
    page: number
    limit: number
    genreId?: ArtistGenreId | null
    regionId?: number
    languageId?: number
}) => {
    const response = await apiClient.get("/artists", { params })
    return response.data
}
// 添加获取歌手列表的接口函数
export const getFeaturedArtists = async (params: {
    page: number
    limit: number
    genreId?: ArtistGenreId | null
    regionId?: number
    languageId?: number
}) => {
    const response = await apiClient.get("/artists/featured", { params })
    return response.data
}

// 修改这些函数以支持分页参数

// 修改 fetchSongsByArtistId 函数
export const fetchSongsByArtistId = async (
    id: string | Array<string> | undefined,
    userId: string | null,
    params?: {
        page?: number
        limit?: number
    },
) => {
    const queryParams = {
        ...(userId ? { userId } : {}),
        ...(params || {}),
    }
    const response = await apiClient.get(`/songs/artist/${id}`, { params: queryParams })
    return response.data.data
}

// 修改 fetchAlbumsByArtistId 函数
export const fetchAlbumsByArtistId = async (
    id: string | Array<string> | undefined,
    userId: string | null,
    params?: {
        page?: number
        limit?: number
    },
) => {
    const queryParams = {
        ...(userId ? { userId } : {}),
        ...(params || {}),
    }
    const response = await apiClient.get(`/albums/artist/${id}`, { params: queryParams })
    return response.data.data
}

// 修改 fetchMvsByArtistId 函数
export const fetchMvsByArtistId = async (
    id: string | Array<string> | undefined,
    userId: string | null,
    params?: {
        page?: number
        limit?: number
    },
) => {
    const queryParams = {
        ...(userId ? { userId } : {}),
        ...(params || {}),
    }
    const response = await apiClient.get(`/mvs/artist/${id}`, { params: queryParams })
    return response.data.data
}

// Add these new functions to fetch new songs and albums
export const fetchNewSongs = async (params: {
    page?: number
    limit?: number
}) => {
    const response = await apiClient.get("/songs/new", { params })
    return response.data.data
}

export const fetchNewAlbums = async (params: {
    page?: number
    limit?: number
}) => {
    const response = await apiClient.get("/albums/new", { params })
    return response.data.data
}

// 添加获取歌曲列表的接口函数
export const fetchSongs = async (params: {
    page?: number
    limit?: number
    genre?: string | null
    sort?: string
    order?: string
}) => {
    const response = await apiClient.get("/songs", { params })
    return response.data.data
}
export const fetchArtistDetail = async (id: string | Array<string> | undefined, userId: string | null) => {
    const params = userId ? { userId } : {}
    const response = await apiClient.get(`/artists/${id}`, {
        params,
    })
    return response.data.data
}

export const fetchPlaylist = async (params: {
    categoryId?: string | null
    page: number
    limit: number
    userId?: string
}) => {
    const response = await apiClient.get(`/playlists`,{params})
    return response.data
}

// 添加获取歌单分类的函数
export const getPlaylistCategories = async () => {
    try {
        const response = await apiClient.get("/playlists/categories")
        return response.data
    } catch (error) {
        console.error("获取歌单分类失败:", error)
        return {
            success: false,
            data: {
                categories: {},
                categoryNames: {},
            },
        }
    }
}

// 添加获取专辑分类的函数
export const getAlbumGenres = async () => {
    const response = await apiClient.get("/albums/genres")
    return response.data
}

// 添加获取歌手分类的函数
export const getArtistGenres = async () => {
    const response = await apiClient.get("/artists/genres")
    return response.data
}

// 获取地区和语言
export const getRegionsAndLanguages = async () => {
    const response = await apiClient.get("/regions-languages")
    return response.data
}

export const getRankingDetail = async (id: string, onlyDetail = false) => {
    // 如果只需要详情，添加查询参数
    const url = onlyDetail ? `/rankings/${id}?onlyDetail=true` : `/rankings/${id}`
    const response = await apiClient.get(url)
    return response.data
}
export const getRankings = async () => {
    const response = await apiClient.get(`/rankings`)
    return response.data
}

// 更新为通用的点赞/收藏功能
export const toggleFavorite = async (params: {
    contentType: "song" | "album" | "playlist" | "mv" | "comment" | "community"
    contentId: ParamValue | number
    userId: number
    action: boolean
}) => {
    const response = await apiClient.post(`/user/favorites`, params)
    return response.data.data
}

// 评论相关的 API 函数
export const fetchComments = async (params: {
    contentId: string
    contentType: "album" | "playlist" | "community" | "mv"
    page?: number
    limit?: number
}): Promise<CommentResponse> => {
    const response = await apiClient.get("/comments", { params })
    return response.data.data
}

// 新增：获取评论回复的 API 函数
export const fetchReplies = async (params: {
    commentId: string
    page?: number
    limit?: number
}): Promise<ReplyResponse> => {
    const response = await apiClient.get(`/comments/${params.commentId}/replies`, {
        params: {
            page: params.page,
            limit: params.limit,
        },
    })
    return response.data.data
}

export const postComment = async (data: {
    contentId: number
    contentType: "album" | "playlist" | "community" | "mv"
    content: string
    userId: number
    parentId?: number
}) => {
    const response = await apiClient.post("/comments", data)
    return response.data.data
}

export const postReply = async (data: {
    contentId: string
    contentType: "album" | "playlist" | "community" | "ranking"
    content: string
    parentId: number
    userId?: string
}) => {
    // 使用 commentId 作为路径参数名称，但函数参数仍使用 parentId 以保持 API 一致性
    const response = await apiClient.post(`/comments/${data.parentId}/reply`, {
        contentId: data.contentId,
        contentType: data.contentType,
        content: data.content,
        userId: data.userId,
    })
    return response.data.data
}

// 添加删除评论的 API 函数
export const deleteComment = async (commentId: number) => {
    const response = await apiClient.delete(`/comments/${commentId}`)
    return response.data
}

// 添加删除回复的 API 函数
export const deleteReply = async (commentId: number, replyId: number) => {
    const response = await apiClient.delete(`/comments/${commentId}/replies/${replyId}`)
    return response.data
}

// Auth API functions
export const loginUser = async (email: string, password: string) => {
    const response = await apiClient.post("/user/login", { email, password })
    return response.data.data
}

export const registerUser = async (username: string, email: string, password: string) => {
    const response = await apiClient.post("/user/register", { username, email, password })
    return response.data.data
}

// Update getUserProfile to always require userId
export const getUserProfile = async (userId: string): Promise<{ data: UserProfile }> => {
    const response = await apiClient.get(`/user/profile/${userId}`)
    return response.data
}

// 重构后的用户收藏API函数 - 使用独立端点
export const getUserLikedSongs = async (params: {
    userId?: string
    page?: number
    limit?: number
}): Promise<{ data: Song[] }> => {
    const response = await apiClient.get("/user/favorites/songs", { params })
    return response.data
}

export const getUserLikedAlbums = async (params: {
    userId?: string
    page?: number
    limit?: number
}): Promise<{ data: Album[] }> => {
    const response = await apiClient.get("/user/favorites/albums", { params })
    return response.data
}

export const getUserLikedMVs = async (params: {
    userId?: string
    page?: number
    limit?: number
}): Promise<{ data: MV[] }> => {
    const response = await apiClient.get("/user/favorites/mvs", { params })
    return response.data
}

export const getUserLikedPlaylists = async (params: {
    userId: string
    limit: number
    created?: boolean
}): Promise<{ data: Playlist[] }> => {
    const response = await apiClient.get("/user/favorites/playlists", { params })
    return response.data
}

export const getUserFollowing = async (params: {
    userId: string
    page?: number
    limit?: number
}): Promise<{
    data: UserFollowing[]
}> => {
    const response = await apiClient.get("/user/following", { params })
    return response.data
}

export const getUserFollowers = async (params: {
    userId?: string
    page?: number
    limit?: number
}): Promise<{
    data: UserFollower[]
}> => {
    const response = await apiClient.get("/user/followers", { params })
    return response.data
}

export const updateUserProfile = async (data: {
    name?: string
    bio?: string
    avatar?: File | string
    cover?: File | string
}): Promise<{ data: Partial<UserProfile> }> => {
    // Create FormData if we have file uploads
    if (data.avatar instanceof File || data.cover instanceof File) {
        const formData = new FormData()

        if (data.name) formData.append("name", data.name)
        if (data.bio) formData.append("bio", data.bio)
        if (data.avatar instanceof File) formData.append("avatar", data.avatar)
        if (data.cover instanceof File) formData.append("cover", data.cover)

        const response = await apiClient.put("/user/profile", formData, {
            headers: {
                "Content-Type": "multipart/form-data",
            },
        })
        return response.data
    } else {
        // Regular JSON request
        const response = await apiClient.put("/user/profile", data)
        return response.data
    }
}

export const followUser = async (userId: string, followedId: string, fansType: number) => {
    const response = await apiClient.post(`/user/follow`, { userId, followedId, fansType })
    return response.data
}

export const unfollowUser = async (userId: string, followedId: string, fansType: number) => {
    const response = await apiClient.delete(
        `/user/unfollow?userId=${userId}?followerId=${followedId}?fansType=${fansType}`,
    )
    return response.data
}

// 添加获取MV列表的接口函数
export const fetchMVs = async (params: {
    page?: number
    limit?: number
    regionId?: number
    versionId?: number
    sort?: "latest" | "popular"
}) => {
    const response = await apiClient.get("/mvs", { params })
    return response.data.data
}

export default apiClient

